package cn.skycity.framework.service.config;

import cn.skycity.framework.core.exception.ServiceException;
import cn.skycity.framework.core.model.Result;
import cn.skycity.framework.core.model.ResultCode;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理数据绑定异常
     * @param bindException
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result<String> bindException(BindException bindException){
        List<String> error = new ArrayList<>();
        BindingResult bindingResult = bindException.getBindingResult();
        bindingResult.getFieldErrors().forEach(s->{
            error.add(s.getField()+s.getDefaultMessage());
        });
        return Result.failed(String.join(",",error));
    }

    @ExceptionHandler(ServiceException.class)
    public Result<String> handleServiceException(ServiceException serviceException){
        return Result.failed(ResultCode.ERROR,serviceException.getMessage());
    }
    /**
     * 处理数据库异常
     * @param sqlException
     * @return
     */
    @ExceptionHandler(SQLException.class)
    public Result<String> bindException(SQLException sqlException){
        return Result.failed(ResultCode.ERROR,sqlException.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Result<String> illegalArgumentException(IllegalArgumentException exception){
        return Result.failed(exception.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public Result<String> runtimeException(RuntimeException runtimeException){
        return Result.failed(ResultCode.ERROR,runtimeException.getMessage());
    }

    @ExceptionHandler(Throwable.class)
    public Result<String> throwable(Throwable throwable){
        return Result.failed(ResultCode.ERROR,throwable.getMessage());
    }
}
